import { reactive, ref, watch, watchEffect } from 'vue'
import postion from '../../common/postion/postion.vue'
import order from '../../common/order/order.vue'
import { goToPage, showModal } from '../../utils/utils'
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
import { moduleTypeRule, objectAny, selectModuleRule } from '../../options/base'
import { hideTabBarAutoShow, homeMenuToPage } from '../../utils/tabCommon'
import { mySchoolStore } from '../../store'
import { baseGetOrderList } from '../../utils/doCloud'
import { takeoutGetOrderList } from '../../utils/foodTakeout/orderMange'
import { toggleModule } from '../../utils/toggleModule'
import { getNoticeList } from '../../utils/common/notice_api'


const db = uniCloud.database()

const defaultMenusData = new Array(new Array(6).fill({
    backImgPath: ``,
    menu_name: `我是默认参数`,
    desc_info: `我是默认参数`,
    menu_status: false,
    bk_color: ``
}))

const defaultCarouselData = new Array(1).fill({
    nav_path: ``,
    desc_info: `我是默认参数`,
    carouselPath: ``
})

var _statusBarHeight:number|undefined|0 =0;
// #ifdef  MP
_statusBarHeight=uni.getSystemInfoSync().statusBarHeight
// #endif

let noticeInterValStop: any = null;

function timerChangeNotice(getList: Array<any>, current: objectAny, time = 10000) {
    noticeInterValStop = setTimeout(() => {
        let currentIndex = 0;
        for (let i = 0; i < getList.length; i++) {
            const item = getList[i];
            if (item._id === current._id) {
                currentIndex = i;
                break
            }
        }

        if (currentIndex >= getList.length - 1) {
            currentIndex = 0;
        } else {
            currentIndex++
        }

        const nextObj = getList[currentIndex];
        current = nextObj;

        console.log(nextObj)

    }, time)
}


; export default {
    components: {
        postion,
        order,
    },
    setup() {
        let tabAutoRun:`ing`|`over`='ing';
        //今日订单选择列表
        const queryModuleList=ref<selectModuleRule>([
            { value: `foodTakeout`, text: `美食外卖` },
            { value: `runErrand`, text: `快递代取` }
        ])
        //今日订单选择的模块
        const selectModule=ref<moduleTypeRule>(`foodTakeout`);
        const statusBarHeight=ref(_statusBarHeight);
        const lineNoticeInfo = ref({});
        const loading = ref(true);
        const swiperMenus = ref(defaultMenusData);
        const carouselList = ref(defaultCarouselData);
        const toDayOrderList = ref<Array<objectAny>>([]);
        const state = mySchoolStore();

        hideTabBarAutoShow().then(async (next)=>{
            await onShowPublic();
            tabAutoRun='over'
            next();
        });

        onShow(()=>{
            if(tabAutoRun===`over`){
                onShowPublic();
            }
        })

        onUnload(() => {
			if (noticeInterValStop) {
				 clearTimeout(noticeInterValStop);
			}
           
        })

        function onShowPublic(){
            return  Promise.allSettled([
                getToDayOrderList(),
                getHomeDataAndRender()
            ])
        }
        // 今日订单下拉选择发生变化
        async function selectChange(type:moduleTypeRule){
            selectModule.value=type;
            uni.showLoading({ title: `正在加载` })
            await getToDayOrderList();
            uni.hideLoading();
        }
        // 获取今日订单信息
        async function getToDayOrderList(){
            try {
                // 根据模块配置 执行对应的函数
                const moduleData = toggleModule[selectModule.value]
                const listObject=await moduleData.getOrderList({
                    queryToDay:true,
                    pageSize:100,
                    module:selectModule.value
                })
                moduleData.getOrderList({
                    queryToDay:true,
                    pageSize:100,
                    module:selectModule.value
                })

                toDayOrderList.value=Object.values(listObject) as Array<objectAny>;
            } catch (error) {
                console.log(`xxxxxx=>  tabbar1 getToDayOrderList 获取订单列表数据异常，异常信息如下： <=xxxxxx`)
                console.error(error)
            }
        }

        function getHomeDataAndRender():Promise<void> {
            return new Promise(async resolve => {
                const [data1, data2, data3] = await Promise.all([
                    //@ts-ignore
                    db.collection(`admin-home-carousel`).where(`show_status==true&&school_id=="${state.mySchool._id}"`).orderBy('sort_id asc').get(),
                    db.collection(`admin-home-menus`).where(`school_id=="${state.mySchool._id}"`).get(),
                    getNoticeList(true)
                ])

                const list = data1.result.data;
                carouselList.value = list.map((it: any) => {
                    const { carousel_icon, ...info } = it;
                    return {
                        ...info,
                        carouselPath: carousel_icon[0].url
                    }
                })

                const { result: { data } } = data2;
                const meusCount = Math.ceil(data.length / 6);
                const meus: any[][] = [];
                for (let i = 0; i < meusCount; i++) {
                    meus[i] = data.splice(0, 6).map((it: any) => {
                        const { menu_icon, ...info } = it;
                        return {
                            ...info,
                            backImgPath: menu_icon[0].url
                        }
                    })
                }
                swiperMenus.value = meus;

                const serverNoticeList = data3;
                if (serverNoticeList.length > 1) {
                    timerChangeNotice(serverNoticeList, lineNoticeInfo.value);
                }
                lineNoticeInfo.value = serverNoticeList[0] || { excerpt: `` };

                loading.value = false;
                resolve();
            })

        }

        const menusToPage = (navInfo:{
            menu_status: boolean;
            nav_path: string;
            _id:string
        }) => {
            homeMenuToPage(navInfo);
        }


        return {
            selectChange,
            selectModule,
            queryModuleList,
            loading,
            lineNoticeInfo,
            carouselList,
            swiperMenus,
            toDayOrderList,
            statusBarHeight,
            menusToPage,
            goToPage,
        }
    }
}